// 对连接作封装
// 文件描述符、缓冲区

#pragma once

#include <iostream>
#include <string>
#include <functional>
#include "InetAddr.hpp"

class Reactor;
class Connection;
using func_t = std::function<void(Connection *)>;

// 每个fd都被视为一个Connection，每个fd都对应有输入输出缓冲区
// listen sockfd套接字也是一样
class Connection
{
public:
  Connection(int sock) : _sock(sock), _R(nullptr)
  {
  }

  int Sockfd()
  {
    return _sock;
  }

  void SetEvents(int events)
  {
    _events = events;
  }

  uint32_t Events()
  {
    return _events;
  }

  // 注册处理方法
  void Register(func_t recver, func_t sender, func_t excepter)
  {
    _recver = recver;
    _sender = sender;
    _excepter = excepter;
  }

  void SetR(Reactor *R)
  {
    _R = R;
  }

  Reactor *R()
  {
    return _R;
  }

  func_t Recver()
  {
    return _recver;
  }
  func_t Sender()
  {
    return _sender;
  }
  func_t Excepter()
  {
    return _excepter;
  }
  void AppendInBuffer(const std::string &buff)
  {
    _inbuffer += buff;
  }
  void AppendOutBuffer(const std::string &buff)
  {
    _outbuffer += buff;
  }
  std::string &Inbuffer()
  {
    return _inbuffer;
  }
  std::string &Outbuffer()
  {
    return _outbuffer;
  }
  bool OutBufferEmpty()
  {
    return _outbuffer.empty();
  }
  void OutBufferRemove(int n)
  {
    _outbuffer.erase(0, n);
  }
  void Close()
  {
    if (_sock >= 0)
    {
      ::close(_sock);
    }
  }
  ~Connection() {}

private:
  int _sock;
  std::string _inbuffer;
  std::string _outbuffer;

  func_t _recver;   // 读方法
  func_t _sender;   // 写方法
  func_t _excepter; // 异常方法

  InetAddr _addr; // 记录连接的客户端IP地址和端口号

  uint32_t _events; // Connection对象中，_sock关心的事件集合

  Reactor *_R;
};